<?php 
/* include the configuration file */
require_once("config.php");

/* include the cache library */
require_once("class/cache.class.php");

/* output gzip enable, when gzip is accepted */
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')){
	// client accepts gzip, so gzip the content
	ob_start("ob_gzhandler");
}else{ 
	// continue normally when gzip is unsupported
	ob_start();
}

/* check if all required parameters exist */
if(array_key_exists("title", $_GET)==true
	&& array_key_exists("ext", $_GET)==true
	&& array_key_exists("w", $_GET)==true){
	// get the requested image width
	$req_width = $_GET["w"];
		
	// define the original filename
	$filename = CONFIG_IMAGE_PATH."/"
		.$_GET["title"].".".$_GET["ext"];
		
	// instanciate the cache object
	$c = new cache();
	
	// generate the cache key
	$cache_key = $c->hash("img".$filename."_".$req_width);
	
	// generate the cache file name
	$cached_filename = CONFIG_CACHE_PATH."/".$cache_key.".".$_GET["ext"];
	
	// when the cached file is not older than
	// the original we can use the cache file
	if(file_exists($cached_filename)===false || (filemtime($cached_filename)<(time()+604800))){
		// load the image file
		$img = imagecreatefromstring(file_get_contents($filename));
		
		// get the current width and height
		list($width, $height) = getimagesize($filename);
		$new_height = round(($req_width * $height) / $width);
		
		// resize the image
		$img_resized = imagecreatetruecolor($req_width, $new_height);

		$white = imagecolorallocate($img_resized, 255, 255, 255);
		imagefill($img_resized, 0, 0, $white);
		
		// copy the resampled image
		imagecopyresampled($img_resized, $img, 0, 0, 0, 0, 
					$req_width, $new_height, $width, $height);
					
		// finally add the file to the cache
		imagejpeg($img_resized,$cached_filename,70);
		
		// finally destroy the image
		imagedestroy($img);
		imagedestroy($img_resized);
	}
	
	// set the expires header to enforce caching
	header("Cache-Control: max-age=604800");
	header('Date: '.gmdate('D, d M Y H:i:s \G\M\T', time()));
	header('Last-Modified: '.gmdate('D, d M Y H:i:s \G\M\T', time()));
	header("Expires: ".gmdate('D, d M Y H:i:s \G\M\T',(time()+604800)));
				
	// output the result
	header("Content-Type: image/jpeg");
	
	// output the image to the browser
	print(file_get_contents($cached_filename));
}
?>
